import { ConfigEnv, UserConfig, loadEnv } from 'vite';
import createVuePlugin from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import svgLoader from 'vite-svg-loader';
import VueSetupExtend from 'vite-plugin-vue-setup-extend';
import path from 'path';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from '@vant/auto-import-resolver';
import postcss from 'postcss';
import pxtorem from 'postcss-pxtorem';
const CWD = process.cwd();

// https://vitejs.dev/config/
export default ({ mode }: ConfigEnv): UserConfig => {
  const { VITE_BASE_URL } = loadEnv(mode, CWD);
  return { 
    base: VITE_BASE_URL,
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },  

    css: {
      postcss: {
        plugins: [ 
          pxtorem({
            rootValue: 144, // 转换为rem的基准值，默认为16
            propList: ['*'], // 需要做转换的属性，如`hight`、`width`、`margin`、`padding`等*，表示全部
            exclude:
              /(node_modules|unitEdit|excludFilterStyle|OutlineSort|freeStyle|layouts|components|project|square)/,
            minPixelValue: 2, // 设置最小转换数值，如果为2，那么2px会被转换，但1px则不会
          }),
        ],
      },
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${path.resolve('src/freeStyle/variables.less')}";`,
          },
          math: 'strict',
          javascriptEnabled: true,
        },
      },
    },
    esbuild: {
      pure: ['console.log', 'debugger'],
    },
    build: {
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            //静态资源分拆打包
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },

      target: 'es2015', // �����������
      cssTarget: 'chrome79', // ��ѡ�������û�Ϊ CSS ��ѹ������һ����ͬ������� target
      chunkSizeWarningLimit: 2000, // chunk ��С��������ƣ��� kbs Ϊ��λ����
      outDir: 'dist', // ָ�����·��
      sourcemap: false, //是否构建source map 文件
      terserOptions: {
        // 生产环境移除console
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      assetsDir: 'static',
      manifest: false,
    },
    plugins: [
      VueSetupExtend(),
      createVuePlugin(),
      vueJsx(),
      Components({
        resolvers: [VantResolver()],
      }),
      // viteMockServe({
      //   mockPath: 'mock',
      //   localEnabled: true,
      // }),
      svgLoader(),
    ],

    server: {
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
      port: 8880,
      host: '0.0.0.0',

      proxy: {
        '/api': 'http://101.34.143.36',
      },
    },
  };
};
